<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <!-- <el-form-item label="所属机构" prop="organizationId">
        <el-input v-model="queryParams.organizationId" placeholder="请选择机构" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->

      <el-form-item label="所属机构" prop="parentId">
        <el-tree-select v-model="queryParams.organizationId" :data="organizationOptions" :props="{
          value: 'organizationId',
          label: 'orgName',
          children: 'children',
        }" value-key="organizationId" placeholder="请选择机构" clearable check-strictly @change="handleQuery" />
      </el-form-item>

      <el-form-item label="业务名称" prop="businessName">
        <el-input v-model="queryParams.businessName" placeholder="请输入业务名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="金额类型" prop="priceType">
        <el-select v-model="queryParams.priceType" placeholder="请选择金额类型" clearable>
          <el-option v-for="dict in price_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="金额" prop="fixedPrice">
        <el-input v-model="queryParams.fixedPrice" placeholder="请输入固定金额值" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="展示顺序" prop="sort">
        <el-input v-model="queryParams.sort" placeholder="请输入展示顺序" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="商品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable>
          <el-option v-for="dict in wdm_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['ruoyi:businessSku:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['ruoyi:businessSku:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['ruoyi:businessSku:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['ruoyi:businessSku:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 业务商品管理列表 -->
    <el-table v-loading="loading" :data="businessSkuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="80px" align="center" prop="skuId" />
      <!-- 如果想展示这个字段，可以根据机构id查询机构名称 -->
      <!-- <el-table-column label="所属机构" align="center" prop="organizationId" /> -->
      <el-table-column label="业务名称" width="120px" align="center" prop="businessName" />
      <el-table-column label="主图" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>

      <!-- 重构信息配置 ref="configContainer" -->
      <el-table-column label="信息配置" align="center" width="300">
        <template #default="scope">
          <div class="config-container">
            <div :class="[
              'config-tags',
              { expanded: expandedConfig === scope.row.skuId },
            ]" :style="{
                maxHeight: expandedConfig === scope.row.skuId ? '9999px' : '60px',
              }" :ref="(el) => setConfigContainer(el, scope.row.skuId)">
              <el-tag v-for="(field, index) in parseInputConfig(
                scope.row.inputConfig
              )" :key="index" class="field-tag" :title="field.label">
                {{ field.label }}
                <el-tag :type="field.required ? 'success' : 'info'" size="small">
                  {{ field.required ? "必填" : "选填" }}
                </el-tag>
              </el-tag>
            </div>

            <!-- 展开/收起按钮 -->
            <el-button v-if="isOverflow(scope.row)" class="expand-btn" @click="toggleExpand(scope.row)">
              {{ expandedConfig === scope.row.skuId ? "收起" : "展开" }}
            </el-button>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="信息配置" align="center" prop="inputConfig" /> -->

      <el-table-column label="交易类型" align="center" prop="priceType">
        <template #default="scope">
          <dict-tag :options="price_type" :value="scope.row.priceType" />
        </template>
      </el-table-column>

      <!-- <el-table-column label="金额" align="center" prop="fixedPrice" /> -->

      <!-- <el-table-column
        label="支付方式"
        align="center"
        prop="payTypeConfig"
      >
        <template #default="scope">
          <dict-tag
            :options="payment_method"
            :value="
              scope.row.payTypeConfig ? scope.row.payTypeConfig.split(',') : []
            "
          />
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="展示顺序" align="center" prop="sort" /> -->

      <el-table-column label="商品状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="备注信息" align="center" prop="remark" />

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:businessSku:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:businessSku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改业务商品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="40%" append-to-body>
      <el-form ref="businessSkuRef" :model="form" :rules="rules" label-width="90px">
        <el-card class="box-card">
          <template #header>
            <div class="clearfix" style="text-align: center">
              
              <span style="font-size: 20px; color: #1890ff">业务基本信息</span>

              <!-- <el-form-item label="机构ID" prop="organizationId">
                <el-input
                  v-model="form.organizationId"
                  placeholder="请输入机构ID"
                />
              </el-form-item> -->

              <el-form-item label="所属机构" prop="organizationId">
                <el-tree-select v-model="form.organizationId" :data="organizationOptions" :props="{
                  value: 'organizationId',
                  label: 'orgName',
                  children: 'children',
                }" value-key="organizationId" placeholder="请选择所属机构" check-strictly />
              </el-form-item>


              <el-form-item label="业务名称" prop="businessName">
                <el-input v-model="form.businessName" placeholder="请输入业务名称" />
              </el-form-item>
              <el-form-item label="展示图" prop="image">
                <image-upload v-model="form.image" />
              </el-form-item>

              <!-- 配置信息重构 -->
              <el-form-item label="信息配置" prop="inputConfig" class="input-config-container">
                <div class="config-preview" v-if="form.inputConfig">
                  <el-tag v-for="(field, index) in parsedInputConfig" :key="index" class="field-tag">
                    {{ field.label }}
                    <el-tag type="success" size="small" v-if="field.required">必填</el-tag>
                    <el-tag type="info" size="small" v-else>选填</el-tag>
                  </el-tag>
                </div>
                <el-button type="primary" @click="openFieldConfigDialog" icon="Setting" class="config-button">
                  配置信息字段
                </el-button>
              </el-form-item>
              <!-- <el-form-item label="信息配置" prop="inputConfig" >
                <el-input
                  v-model="form.inputConfig"
                  type="textarea"
                  placeholder="请输入内容"
                  rows="8"
                />
              </el-form-item> -->

              <el-form-item label="金额类型" prop="priceType">
                <el-select v-model="form.priceType" placeholder="请选择金额类型">
                  <el-option v-for="dict in price_type" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="固定金额值" prop="fixedPrice">
                <el-input v-model="form.fixedPrice" placeholder="请输入固定金额值" />
              </el-form-item>
              <el-form-item label="支付方式" prop="payTypeConfig">
                <el-checkbox-group v-model="form.payTypeConfig">
                  <el-checkbox v-for="dict in payment_method" :key="dict.value" :label="dict.value">
                    {{ dict.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="展示顺序" prop="sort">
                <el-input v-model="form.sort" placeholder="请输入展示顺序" />
              </el-form-item>
              <el-form-item label="商品状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in wdm_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="删除标志" prop="delFlag">
                <el-radio-group v-model="form.delFlag">
                  <el-radio v-for="dict in del_flag" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注信息" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>


            </div>
          </template>
        </el-card>
        
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增：信息字段配置对话框 -->
    <el-dialog title="信息字段配置" v-model="fieldConfigDialogVisible" width="700px" append-to-body>
      <div class="field-config-container">
        <div class="fixed-fields">
          <h3>固定字段</h3>
          <div class="field-item">
            <span class="field-label">员工编号</span>
            <el-tag type="success" size="small">必填</el-tag>
          </div>
          <div class="field-item">
            <span class="field-label">所属机构</span>
            <el-tag type="success" size="small">必填</el-tag>
          </div>
        </div>

        <div class="custom-fields">
          <h3>
            自定义字段
            <el-button type="primary" size="small" @click="addCustomField">添加字段</el-button>
          </h3>
          <div class="field-list">
            <div v-for="(field, index) in customFields" :key="index" class="field-item">
              <el-input v-model="field.label" placeholder="字段名称" style="width: 180px; margin-right: 10px" />
              <el-input v-model="field.field" placeholder="字段标识" style="width: 180px; margin-right: 10px" />
              <el-checkbox v-model="field.required" style="margin-right: 10px">
                必填
              </el-checkbox>
              <el-button type="danger" icon="Delete" circle @click="removeCustomField(index)" size="small" />
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="fieldConfigDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveFieldConfig">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BusinessSku">
import { listOrganization } from "@/api/ruoyi/organization";
import { ref, nextTick } from "vue";

import {
  listBusinessSku,
  getBusinessSku,
  delBusinessSku,
  addBusinessSku,
  updateBusinessSku,
} from "@/api/ruoyi/businessSku";

const { proxy } = getCurrentInstance();
const { wdm_status, price_type, payment_method, del_flag } = proxy.useDict(
  "wdm_status",
  "price_type",
  "payment_method",
  "del_flag"
);

const businessSkuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 新增字段配置相关变量
const fieldConfigDialogVisible = ref(false);
const customFields = ref([]);
const parsedInputConfig = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    organizationId: null,
    businessName: null,
    image: null,
    inputConfig: null,
    priceType: null,
    fixedPrice: null,
    payTypeConfig: null,
    sort: null,
    status: null,
  },
  rules: {
    organizationId: [
      { required: true, message: "机构ID不能为空", trigger: "blur" },
    ],
    inputConfig: [
      { required: true, message: "信息配置不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询业务商品管理列表 */
function getList() {
  loading.value = true;
  listBusinessSku(queryParams.value).then((response) => {
    // businessSkuList.value = response.rows;
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    businessSkuList.value = response.rows.filter(
      item => item.delFlag !== "2"
    );
    total.value = response.total;
    loading.value = false;
  });
}

// 打开字段配置对话框
function openFieldConfigDialog() {
  // 解析现有的配置
  try {
    if (form.value.inputConfig) {
      const config = JSON.parse(form.value.inputConfig);
      // 过滤掉固定字段
      customFields.value = config.filter(
        (field) => field.field !== "jobCode" && field.field !== "orgName"
      );
    } else {
      customFields.value = [];
    }
  } catch (e) {
    customFields.value = [];
  }

  fieldConfigDialogVisible.value = true;
}

// 添加自定义字段
function addCustomField() {
  customFields.value.push({
    field: "",
    label: "",
    required: true,
  });
}

// 移除自定义字段
function removeCustomField(index) {
  customFields.value.splice(index, 1);
}

// 保存字段配置
function saveFieldConfig() {
  // 创建固定字段
  const fixedFields = [
    { field: "jobCode", label: "员工编号", required: true },
    { field: "orgName", label: "所属机构", required: true },
  ];

  // 组合所有字段
  const allFields = [...fixedFields, ...customFields.value];

  // 验证字段
  for (let field of allFields) {
    if (!field.label) {
      proxy.$modal.msgError("字段名称不能为空");
      return;
    }
    if (!field.field) {
      proxy.$modal.msgError("字段标识不能为空");
      return;
    }
  }

  // 保存到表单
  form.value.inputConfig = JSON.stringify(allFields);
  parsedInputConfig.value = allFields;

  fieldConfigDialogVisible.value = false;
}

// 解析输入配置为数组
function parseInputConfig(inputConfig) {
  try {
    return JSON.parse(inputConfig);
  } catch (e) {
    return [];
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    skuId: null,
    organizationId: null,
    businessName: null,
    image: null,
    inputConfig: null,
    priceType: null,
    fixedPrice: null,
    payTypeConfig: [],
    sort: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("businessSkuRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.skuId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加业务商品管理";
}

/** 修改按钮操作 */
// 修改按钮操作 - 更新解析后的配置
function handleUpdate(row) {
  reset();
  const _skuId = row.skuId || ids.value;
  getBusinessSku(_skuId).then((response) => {
    form.value = response.data;
    form.value.payTypeConfig = form.value.payTypeConfig.split(",");

    // 解析输入配置
    try {
      if (form.value.inputConfig) {
        parsedInputConfig.value = JSON.parse(form.value.inputConfig);
      } else {
        parsedInputConfig.value = [];
      }
    } catch (e) {
      parsedInputConfig.value = [];
    }

    open.value = true;
    title.value = "修改业务商品管理";
  });
}

// function handleUpdate(row) {
//   reset();
//   const _skuId = row.skuId || ids.value;
//   getBusinessSku(_skuId).then((response) => {
//     form.value = response.data;
//     form.value.payTypeConfig = form.value.payTypeConfig.split(",");
//     open.value = true;
//     title.value = "修改业务商品管理";
//   });
// }

/** 提交按钮 */
function submitForm() {
  proxy.$refs["businessSkuRef"].validate((valid) => {
    if (valid) {
      form.value.payTypeConfig = form.value.payTypeConfig.join(",");
      if (form.value.skuId != null) {
        updateBusinessSku(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBusinessSku(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _skuIds = row.skuId || ids.value;
  proxy.$modal
    .confirm('是否确认删除业务商品管理编号为"' + _skuIds + '"的数据项？')
    .then(function () {
      return delBusinessSku(_skuIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/businessSku/export",
    {
      ...queryParams.value,
    },
    `businessSku_${new Date().getTime()}.xlsx`
  );
}

/** 新增 */

const expandedConfig = ref(null);
const configContainer = ref(null);

const configContainerMap = new Map(); // ✅ 存储每行的 DOM

// 存储每行的 DOM
function setConfigContainer(el, skuId) {
  if (el) {
    configContainerMap.set(skuId, el);
  } else {
    configContainerMap.delete(skuId);
  }
}
// 判断是否溢出
function isOverflow(row) {
  if (!configContainerMap.has(row.skuId)) return false;

  nextTick(() => {
    const container = configContainerMap.get(row.skuId);
    if (container) {
      setTimeout(() => {
        container._isOverflow = container.scrollHeight > 60;
      }, 50); // 延迟确保 DOM 完全渲染
    }
  });

  return configContainerMap.get(row.skuId)?._isOverflow || false;
}

// 切换展开状态
function toggleExpand(row) {
  expandedConfig.value = expandedConfig.value === row.skuId ? null : row.skuId;
}


// 机构信息下拉框
const organizationOptions = ref([]);

/** 查询机构信息下拉树结构 */
function getTreeselect() {
  listOrganization().then((response) => {
    organizationOptions.value = [];
    const data = { organizationId: 0, orgName: "顶级节点", children: [] };
    data.children = proxy.handleTree(
      response.data,
      "organizationId",
      "parentId"
    );
    organizationOptions.value.push(data);
  });
}

/** 获取列表 */
getList();
// 获取机构信息下拉树结构
getTreeselect();

// toggleExpand(row);
</script>

<!-- 列表页字段标签样式 -->
<style scoped>
.config-container {
  position: relative;
  padding-right: 60px;
  /* 为展开按钮留出空间 */
}

.config-tags {
  max-height: 60px;
  overflow-y: hidden;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  transition: max-height 0.3s ease-out;
}

.field-tag {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.expand-btn {
  position: absolute;
  right: 0;
  bottom: 0;
  z-index: 1;
  padding: 2px 8px;
  font-size: 12px;
}

/* 列表页字段标签样式 */
.config-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.field-tag {
  display: inline-flex;
  align-items: center;
  margin-bottom: 5px;
}

.required-tag {
  margin-left: 5px;
}

/* 表单页信息配置区域 */
.input-config-container {
  margin-bottom: 20px;
}

.config-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 50px;
}

.field-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.config-button {
  width: 100%;
}

/* 字段配置对话框样式 */
.field-config-container {
  padding: 15px;
}

.fixed-fields,
.custom-fields {
  margin-bottom: 25px;
}

.field-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

.field-label {
  flex: 1;
  margin-right: 15px;
}

.custom-fields h3 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.field-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>
